<?php

namespace App\Admin\Controllers;

use App\Admin\Actions\Grid\RowActions\ResetPassword;
use App\Models\Company;
use App\Support\Data;
use Dcat\Admin\Admin;
use Dcat\Admin\Form;
use Dcat\Admin\Grid;
use Dcat\Admin\Http\Auth\Permission;
use Dcat\Admin\Http\Repositories\Administrator;
use Dcat\Admin\Models\Administrator as AdministratorModel;
use Dcat\Admin\Show;
use Dcat\Admin\Support\Helper;
use Dcat\Admin\Widgets\Tree;
use Dcat\Admin\Http\Controllers\AdminController;
use Illuminate\Support\Facades\Log;

class AgentController extends AdminController
{
    public function title()
    {
        return '人员管理';
    }


    protected function grid()
    {
        return Grid::make(Administrator::with(['roles']), function (Grid $grid) {
            // $grid->setActionClass(Grid\Displayers\DropdownActions::class);
            $grid->disablePerPages();
            $grid->paginate(8);
            $grid->disableViewButton();
            $grid->scrollbarX();
            $grid->withBorder();
            $grid->addTableClass(['table-text-center']);

            $grid->model()->setConstraints([
                'key1' => 'v1',
                'key2' => 'v2',
            ]);

            $grid->column('id', 'ID')->sortable();
            $grid->column('username');
            $grid->column('name', '真实姓名');
            $grid->column('employee_number', '员工编号');
            $grid->column('region', '区域')->display(function ($id) {
                $arr = Data::getRegion();
                return isset($arr[$id]) ? $arr[$id] : ' - ';
            });
            $grid->column('company_id', '公司')->display(function ($id) {
                return Company::find($id)->company_name ?? ' - ';
            });

            if (config('admin.permission.enable')) {
                $grid->column('roles')->pluck('name')->label('primary', 3);

                // $permissionModel = config('admin.database.permissions_model');
                // $roleModel = config('admin.database.roles_model');
                // $nodes = (new $permissionModel())->allNodes();
                // $grid->column('permissions')
                //     ->if(function () {
                //         return !$this->roles->isEmpty();
                //     })
                //     ->showTreeInDialog(function (Grid\Displayers\DialogTree $tree) use (&$nodes, $roleModel) {
                //         $tree->nodes($nodes);

                //         foreach (array_column($this->roles->toArray(), 'slug') as $slug) {
                //             if ($roleModel::isAdministrator($slug)) {
                //                 $tree->checkAll();
                //             }
                //         }
                //     })
                //     ->else()
                //     ->display('');
            }

            $grid->column('created_at')->sortable();
            $grid->column('status', '状态')->switch();
            // $grid->column('updated_at')->sortable();

            // $grid->quickSearch(['id', 'name', 'username']);

            $grid->showQuickEditButton();
            $grid->enableDialogCreate();
            $grid->showColumnSelector();
            $grid->disableEditButton();

            $grid->model()->where('is_external', 1);
            $grid->model()->orderBy('created_at', 'desc')->orderBy('id', 'desc');
            // 如果是项目管理员查看对应公司下所有的人
            if (Admin::user()->isRole('project-manager')) {
                $grid->model()->where('company_id', Admin::user()->company_id);
            }

            // 如果是大区管理员查看对应公司下大区所有的人
            if (Admin::user()->isRole('regional-supervisor')) {
                $grid->model()->where('company_id', Admin::user()->company_id)->where('region', Admin::user()->region);
            }
            $grid->actions(function (Grid\Displayers\Actions $actions) {
                if ($actions->getKey() == AdministratorModel::DEFAULT_ID) {
                    $actions->disableDelete();
                } else {
                    $actions->append(new ResetPassword());
                }
            });

            $grid->filter(function (Grid\Filter $filter) {
                $filter->like('username');
                $filter->like('name');
                $filter->equal('employee_number', '员工编号')->placeholder('请输入员工编号');
                // 超级管理员显示所有公司
                if (Admin::user()->isAdministrator() || Admin::user()->isRole('项目经理')) {
                    // 其他项目经理、区域经理只显示自己公司、区域
                    $filter->equal('company_id', '所属公司')->select(Company::pluck('company_name', 'id'));
                    $filter->equal('region', '区域')->select(Data::getRegion());
                } else {

                    if (Admin::user()->isRole('project-manager')) {
                        $filter->equal('region', '区域')->select(Data::getRegion());
                    }
                }
            });
        });
    }

    protected function detail($id)
    {
        return Show::make($id, Administrator::with(['roles']), function (Show $show) {
            $show->field('id');
            $show->field('username');
            $show->field('name');

            $show->field('avatar', __('admin.avatar'))->image();

            if (config('admin.permission.enable')) {
                $show->field('roles')->as(function ($roles) {
                    if (!$roles) {
                        return;
                    }

                    return collect($roles)->pluck('name');
                })->label();

                $show->field('permissions')->unescape()->as(function () {
                    $roles = $this->roles->toArray();

                    $permissionModel = config('admin.database.permissions_model');
                    $roleModel = config('admin.database.roles_model');
                    $permissionModel = new $permissionModel();
                    $nodes = $permissionModel->allNodes();

                    $tree = Tree::make($nodes);

                    $isAdministrator = false;
                    foreach (array_column($roles, 'slug') as $slug) {
                        if ($roleModel::isAdministrator($slug)) {
                            $tree->checkAll();
                            $isAdministrator = true;
                        }
                    }

                    if (!$isAdministrator) {
                        $keyName = $permissionModel->getKeyName();
                        $tree->check(
                            $roleModel::getPermissionId(array_column($roles, $keyName))->flatten()
                        );
                    }

                    return $tree->render();
                });
            }

            $show->field('created_at');
            $show->field('updated_at');
        });
    }

    public function form()
    {
        return Form::make(Administrator::with(['roles']), function (Form $form) {
            $userTable = config('admin.database.users_table');

            $connection = config('admin.database.connection');

            $id = $form->getKey();

            $form->display('id', 'ID');

            $form->text('username', '登陆名')
                ->required()
                ->creationRules(['required', "unique:{$connection}.{$userTable}"])
                ->updateRules(['required', "unique:{$connection}.{$userTable},username,$id"]);
            $form->text('name', '姓名')->placeholder('请输入真实姓名')->required();
            $form->image('avatar', trans('admin.avatar'))->autoUpload()->saving(function ($path) {
                return httpToHttps($path);
            });

            if ($id) {
                $form->password('password', trans('admin.password'))
                    ->minLength(5)
                    ->maxLength(20)
                    ->customFormat(function () {
                        return '';
                    });
            } else {
                $form->password('password', trans('admin.password'))
                    ->required()
                    ->minLength(5)
                    ->maxLength(20);
            }

            $form->password('password_confirmation', trans('admin.password_confirmation'))->same('password');

            $form->hidden('is_external')->value(1);
            $form->hidden('status')
                // ->customFormat(function ($v) {
                //     return $v == 1 ? 1 : 0;
                // })
                ->saving(function ($v) {
                    return $v;
                });


            $form->ignore(['password_confirmation']);
            $form->distpicker([
                'province_id' => '省份',
                'city_id' => '市',
                'district_id' => '区'
            ], '地域选择');
            $form->text('employee_number', '员工编号')->required();
            $form->mobile('phone', '手机号码')->rules('required|regex:/^1[3-9]\d{9}$/', ['regex' => '手机号码格式不正确', 'required' => '请填写手机号码'])->required();

            // if (Admin::user()->isRole('project-manager')) {
            $region = Data::getRegion();
            if (Admin::user()->isRole('regional-supervisor')) {
                $value = array_search(Admin::user()->region, array_keys($region));
                $region = [$value => $region[$value]];
            }
            $form->select('region', '区域')->options($region)->required();
            // } else {
            //     $form->hidden('region');
            // }

            // $form->text('phone', '手机号')->required();
            // $form->text('number', '分配名额数')->required();
            $form->radio('status', '状态')->options([0 => '禁用', 1 => '启用'])->default(1);

            $form->multipleSelect('roles', trans('admin.roles'))
                ->options(function () {
                    $roleModel = config('admin.database.roles_model');
                    // return $roleModel::where('is_external', 1)->pluck('name', 'id');
                    if (Admin::user()->isRole('project-manager')) {
                        return $roleModel::where('is_external', 1)->where('slug', '<>', 'project-manager')->pluck('name', 'id');
                    } elseif (Admin::user()->isRole('regional-supervisor')) {
                        return $roleModel::where('is_external', 1)->where('slug', 'agent')->pluck('name', 'id');
                    } else {

                        return $roleModel::where('is_external', 1)->pluck('name', 'id');
                    }
                })->required()
                ->customFormat(function ($v) {
                    return array_column($v, 'id');
                });
            if (Admin::user()->isRole('administrator') || Admin::user()->isRole('项目经理')) {
                $form->select('company_id', '公司')
                    ->options(function () {
                        return Company::pluck('company_name', 'id');
                    });
                // ->customFormat(function ($v) {
                //     return array_column($v, 'id');
                // });
            } else {
                $form->hidden('company_id');
                $form->hidden('admin_id');
            }

            $form->display('created_at', trans('admin.created_at'));
            $form->display('updated_at', trans('admin.updated_at'));

            if ($id == AdministratorModel::DEFAULT_ID) {
                $form->disableDeleteButton();
            }
        })->saving(function (Form $form) {

            $form->admin_id = Admin::user()->id;
            // if (!empty($form->input('region'))) {
            //     $form->region = $form->input('region');
            // } else {
            //     $form->region = isset(Admin::user()->region) && !empty(Admin::user()->region) ? Admin::user()->region : null;
            // }

            if ((!Admin::user()->isRole('administrator')) && (!Admin::user()->isRole('项目经理'))) {

                $form->company_id = Admin::user()->company_id;
            }

            if ($form->password && $form->model()->get('password') != $form->password) {
                $form->password = bcrypt($form->password);
            }

            if (!$form->password) {
                $form->deleteInput('password');
            }
        })->saved(function (Form $form) {
            $data = $form->updates();
            Log::info(' ==== 客户管理操作 保存客户编辑数据: ====' . json_encode($data));
        });
    }

    public function destroy($id)
    {
        if (in_array(AdministratorModel::DEFAULT_ID, Helper::array($id))) {
            Permission::error();
        }

        return parent::destroy($id);
    }
}
